package com.cndw.kungfu.model.disciple;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.disciple.domain.Disciple;
import com.cndw.kungfu.model.disciple.domain.DiscipleMode;
import com.cndw.kungfu.model.disciple.domain.DiscipleRein;


@Service
public class DiscipleServer{
	@Autowired
	private DiscipleManager discipleManager;
		

	
	/**
	 * 获取玩家门派信息
	 * @param playerId
	 * @return
	 */
	public PlayerMartial getByPlayerId(long playerId){
		ConcurrentHashMap<Long, PlayerMartial> martialMap = Context.getDataServer().getPlayerMartialMap();
		if (!martialMap.containsKey(playerId)) {		
			synchronized (martialMap) {
				if (!martialMap.containsKey(playerId)) {
					try {
						Player player = Context.getPlayerServer().getByPlayerId(playerId);
						if (player == null) {
							return null;
						}
						Map<Integer, List<DiscipleRein>> reinBuffer = player.getDataInfo().getReinBuffer();					
						Map<Integer, Disciple> disciples = discipleManager.getDiscipleMapDB(playerId);					
						PlayerMartial playerMartial = new PlayerMartial(disciples,reinBuffer);
						martialMap.put(playerId, playerMartial);	
					} catch (Exception e) {
						e.printStackTrace();
					}
				
				}				
			}			
		}
		return martialMap.get(playerId);
	}

	/**
	 * 获取系统徒弟
	 * @param id
	 * @return
	 */
	public DiscipleMode getDiscipleMode(int discipleId){
		return Context.getCacheCenter().getDiscipleMode(discipleId);
	}
	
	public Disciple createDisciple(long playerId,int quality,int spcSign) {		
		DiscipleRein rein = discipleManager.makeRefresh(1, quality,spcSign,false);
		Disciple disciple = discipleManager.createDisciple(playerId, rein);
		return disciple;
	}
	
	
	public int insertDisciple(Disciple disciple) {
		return discipleManager.insertDisciple(disciple);
	}

	public void studyGest(long playerId, int id, int getsId) {
		try {
			PlayerMartial playerMartial = Context.getDiscipleServer().getByPlayerId(playerId);
			Disciple disciple = playerMartial.getDiscipleById(id);
			if (disciple != null && disciple.getGestSign() != getsId) {
				disciple.setGestSign(getsId);
				disciple.clacPropertys();
				disciple.commitSync();
				if (disciple.getCampId() > 0 ) {
					Player player = Context.getPlayerServer().getByPlayerId(playerId);
					Context.getPlayerServer().clacProperties(player);					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}


}
